package com.icode.cas.spinLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-14 19:14
 */
public class SpinLock {

    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "> myLock");

        //自旋锁
        while (!atomicReference.compareAndSet(null, thread)){
            System.out.println(".");
            //延时几秒
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName() + "> myUnLock");
        atomicReference.compareAndSet(thread, null);
    }
}
